package com.stone.java8;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;

import java.util.Arrays;

/**
 * desc   : 类实例方法引用   Person::compareByName
 * author : stone
 * email  : aa86799@163.com
 * time   : 13/03/2017 10 27
 */
public class CIMethodReferenceActi extends Activity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        methodReference();
    }

    void methodReference() {//方法引用
        Person p1 = new Person("stone");
        Person p2 = new Person("sun");
        boolean result = isLarge((v1, v2) -> v1.compareByName(v2), p1, p2);
        System.out.println("p1 排序在 p2 后: " + result);

        result = isLarge(Person::compareByName, p1, p2);
        System.out.println("p1 排序在 p2 后: " + result);

        printInfo(value -> value.printInfo(), p1);
        printInfo(Person::printInfo, p2);

        Integer[] ary = {2, 8, 1, 5, 6, 3, 4};
        Arrays.sort(ary, (o1, o2) -> o1.compareTo(o2));
        Arrays.sort(ary, Integer::compareTo);


        //内部实例化
        isLarge((v1, v2) -> v1.compareByName(v2));//lambda expression
        isLarge(Person::compareByName);//method reference
    }

    public boolean isLarge(Compare<Person> c, Person p1, Person p2) {
        return c.compareTo(p1, p2);
    }


    public interface Compare<T> {
        boolean compareTo(T v1, T v2);
    }

    static class Person {

        public Person() {

        }

        public Person(String name) {
            this.name = name;
        }

        String name;
        Long birthday;

        public Long getBirthday() {
            return birthday;
        }

        public String getName() {
            return name;
        }

        public boolean compareByName(Person b) {
            int result = this.name.compareToIgnoreCase(b.name);
            if (result == 1) {
                return true;
            } else {
                return false;
            }
        }

        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", birthday=" + birthday +
                    '}';
        }

        public void printInfo() {
            System.out.println(toString());
        }
    }


    /*****display*****/

    public void printInfo(Display<Person> d, Person person) {
        d.display(person);
    }

    public interface Display<T> {
        void display(T value);
    }

    /**内部实例化*/
    public boolean isLarge(Compare<Person> c) {
        Person p1 = new Person("stone");
        Person p2 = new Person("austin");
        return c.compareTo(p1, p2);
    }

}
